<?php

namespace App\Http\Controllers\admin;

use App\Http\Controllers\Controller;
use App\Models\Approval;
use App\Models\ApprovalFlow;
use App\Services\ApprovalFlowService;
use Illuminate\Http\Request;

class ApprovalFlowController extends Controller
{
    protected $ApprovalFlowService;
    public function __construct(ApprovalFlowService $ApprovalFlowService)
    {
        $this->ApprovalFlowService = $ApprovalFlowService;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $title = $request->title;
        $pageSize = $request->pageSize ?: 10;
        $page = $request->page ?: 1;
        $page = $page * $pageSize - $pageSize;

        $sql = $this->ApprovalFlowService->get($title);
        $sql->where('company_id',$request->company_id);
        $total = $sql->count();
        $data = $sql->skip($page)->take($pageSize)->orderBy('created_at','desc')->get();
        foreach ($data as $k => $v) {
            $data[$k]->status = $v->status == 1 ? true : false;
        }

        $models = Approval::MODELS;
        return response()->json(['code' => 200, 'message' => '操作成功','page'=>$page,'pageSize'=>$pageSize,'total'=>$total,'data'=>$data,'models'=>$models]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $POSTONLY = ApprovalFlow::POSTONLY;
        $input = $request->only($POSTONLY);
        $data = $this->ApprovalFlowService->insert($input);
        return response()->json(['code' => 200, 'message' => '操作成功','data'=>$data]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request)
    {
        $POSTONLY = ApprovalFlow::POSTONLY;
        $input = $request->only($POSTONLY);
        $input['id'] = $request->id;
        $data = $this->ApprovalFlowService->update($input);
        return response()->json(['code' => 200, 'message' => '操作成功','data'=>$data]);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function delete($id)
    {
        if(!$id){
            return response()->json(['code' => 404, 'message' => '请选择要操作的记录']);
        }
        $data = ApprovalFlow::find($id);
        $data->delete();
        return response()->json(['code' => 200, 'message' => '操作成功']);
    }



}
